//
//  ZCDetaileListViewController.m
//  VoiceMusic
//
//  Created by dllo on 15/10/21.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCDetaileListViewController.h"
#import "ZCDetailListModel.h"
#import "ZCDetailListTableViewCell.h"
#import "ZCAFNetWork.h"
#import "ZCPlayMusicTool.h"
#import "ZCBaseSqliteTool.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import "ZCDownLoadTool.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ZCDetaileListViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) NSMutableArray *headViewData;
@property (nonatomic, strong) NSMutableArray *songArr;
@property (nonatomic, copy) NSString *picUrl;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UIImageView *headTitleImageView;
@property (nonatomic, copy) NSString *headImage;
@property (nonatomic, strong) UILabel *authorName;
@property (nonatomic, copy) NSString *author;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, copy) NSString *titleText;
@property (nonatomic, strong) UILabel *detailTitleLabel;
@property (nonatomic, copy) NSString *detailTitleText;
@property (nonatomic, copy) NSString *lastStr;
@property (nonatomic, assign) NSInteger num;
@end

@implementation ZCDetaileListViewController
#pragma mark 初始胡
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.headViewData = [NSMutableArray array];
        self.songArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"750365_105833058_2"]];
    [self createListTableViewData];
    [self createListTableView];
    //返回键
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [leftButton addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark 返回
- (void)returnClick:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 创建视图
- (void)createListTableView
{
    self.listTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.listTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.listTableView];
    [self.listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-49);
    }];
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    self.listTableView.emptyDataSetSource = self;
    self.listTableView.emptyDataSetDelegate = self;
    self.listTableView.rowHeight = 60;
    self.listTableView.bounces = NO;
    // 头视图
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 220)];
    [self.view addSubview:self.headView];
    self.listTableView.tableHeaderView = self.headView;
    // 头视图图片
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 220)];
    [self.headView addSubview:self.headImageView];
    // 头像
    self.headTitleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 80, 40, 40)];
    self.headTitleImageView.layer.cornerRadius = 20;
    self.headTitleImageView.layer.masksToBounds = YES;
    [self.headView addSubview:self.headTitleImageView];
    
    // 作者名字
    self.authorName = [[UILabel alloc] initWithFrame:CGRectMake(65, 80, 150, 40)];
    [self.headView addSubview:self.authorName];
    self.authorName.textColor = [UIColor whiteColor];
    [self.authorName setFont:[UIFont fontWithName:@"Helvetica-Bold" size:17]];
    
    // 标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 120, WIDTH - 30, 40)];
    [self.headView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    [self.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:19]];
    
    // 详细介绍
    self.detailTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 160, WIDTH - 30, 40)];
    [self.headView addSubview:self.detailTitleLabel];
    self.detailTitleLabel.textColor = [UIColor whiteColor];
    [self.detailTitleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14]];
    
}
#pragma mark 解析数据
- (void)createListTableViewData
{
    NSString *front = @"?agent=none&longitude=0.0&utdid=UyKT11zHlGYBACzJ7%2FDxmdxJ&net=2&from=android&os=5.0.2&v=v8.1.0.2015071519&alf=700159&api_version=1.0&imei=863583022034533&latitude=0.0&f=168&resolution=720x1280&language=zh&user_id=0";
    NSString *url = [NSString stringWithFormat:@"http://api.songlist.ttpod.com/songlists/%@%@",self.myId,front];
    [ZCAFNetWork getUrl:url body:nil result:ZCJSON headerFile:nil success:^(id result) {
        self.picUrl = result[@"image"][@"pic"];
        self.author = result[@"owner"][@"nick_name"];
        self.headImage = result[@"owner"][@"portrait_pic"];
        self.titleText = result[@"title"];
        self.detailTitleText = result[@"desc"];
        self.songArr = [ZCDetailListModel baseModelByArr:result[@"songs"]];
        for (NSInteger i = 0; i<self.songArr.count; i++) {
            ZCDetailListModel *model = self.songArr[i];
            if(model.auditionList.count == 0){
                [self.songArr removeObjectAtIndex:i];
            }
        }
        [self.listTableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"error = %@",error);
    }];
}
#pragma mark tableview方法的实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.songArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *reuse=@"reuse";
    ZCDetailListTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell =[[ZCDetailListTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 头视图内容
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.picUrl]placeholderImage:[UIImage imageNamed:@"3187"]];
    
    // cell赋值
    cell.backgroundColor = [UIColor clearColor];
    ZCDetailListModel *model = self.songArr[indexPath.row];
    // 歌名 歌手名
    cell.titleLabel.text = model.name;
    cell.detailLabel.text = model.singerName;
    cell.button.tag = self.num;
    
    if(InTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        
        [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang-1"] forState:UIControlStateNormal];
        [cell.button addTarget:self action:@selector(cancleSave:) forControlEvents:UIControlEventTouchUpInside ];
        
    }else if (NotInTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
        [cell.button addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside ];
    }else{
        [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
        [cell.button addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside ];
    }
    [cell.loadButton addTarget:self action:@selector(load:) forControlEvents:UIControlEventTouchUpInside];
    cell.loadButton.tag = self.num;
    self.num ++;
    return cell;
}

#pragma mark 点击方法
-(void)save:(UIButton *)bu{
    
    ZCDetailListTableViewCell *cell = (ZCDetailListTableViewCell *)bu.superview.superview;
    //    NSIndexPath *index = [self.listTableView indexPathForSelectedRow];
    //    ZCDetailListTableViewCell *cell = [self.listTableView cellForRowAtIndexPath:index];
    [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang-1"] forState:UIControlStateNormal];
    ZCDetailListModel *model = self.songArr[bu.tag];
    if(InTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        
        [[ZCBaseSqliteTool shareZCMusicDataTool] deleteMusic:model];
        
    }else if (NotInTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        
        [[ZCBaseSqliteTool shareZCMusicDataTool] insertMusic:model];
    }
    
    
    
    [cell.button removeTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.button addTarget:self action:@selector(cancleSave:) forControlEvents:UIControlEventTouchUpInside ];
    
}

#pragma mark 点击方法
-(void)cancleSave:(UIButton *)bu{
    ZCDetailListTableViewCell *cell = (ZCDetailListTableViewCell *)bu.superview.superview;
    
    //    NSIndexPath *index = [self.listTableView indexPathForSelectedRow];
    //    ZCDetailListTableViewCell *cell = [self.listTableView cellForRowAtIndexPath:index];
    
    ZCDetailListModel *model = self.songArr[bu.tag];
    if(InTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        
        [[ZCBaseSqliteTool shareZCMusicDataTool] deleteMusic:model];
        
    }else if (NotInTable == [[ZCBaseSqliteTool shareZCMusicDataTool] isInTable:model]){
        
        [[ZCBaseSqliteTool shareZCMusicDataTool] insertMusic:model];
    }
    
    [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
    
    [cell.button removeTarget:self action:@selector(cancleSave:) forControlEvents:UIControlEventTouchUpInside];
    [cell.button addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside ];
}

#pragma mark 点击方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZCDetailListModel *model = self.songArr[indexPath.row];
    
    //    if(model.auditionList.count == 0) {
    //
    //        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"版权不支持" preferredStyle:UIAlertControllerStyleAlert];
    //        [self presentViewController:alter animated:YES completion:nil];
    //
    //        [self dismissViewControllerAnimated:YES completion:^{
    //        }];
    //        return;
    //    }
    if(model.mvList.count == 0) {
        
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"消息" message:@"版权不支持" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alter animated:YES completion:nil];
        
        [self dismissViewControllerAnimated:YES completion:^{
        }];
        return;
    }
    
    //判断歌曲是否重复点击
    if([self.lastStr isEqualToString:model.auditionList[0][@"url"]])return;
    
    self.lastStr = model.auditionList[0][@"url"];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:model.name,@"name",model.singerName,@"nameSinge",model.mvList[0][@"picUrl"],@"heat",model.auditionList[0][@"url"],@"url",nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:self userInfo:dic];
    
    [[NSUserDefaults standardUserDefaults] setObject:model.auditionList[0][@"url"] forKey:@"url"];
    //播放音乐
    [ZCPlayMusicTool getPlay:model.auditionList[0][@"url"]];
    [ZCPlayMusicTool sharePlay].urlMusic = model.auditionList[0][@"url"];
    //发送监听列表的属性
    NSDictionary *arrDic = [NSDictionary dictionaryWithObjectsAndKeys:self.songArr,@"arr", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"arr" object:nil userInfo:arrDic];
    
    [ZCPlayMusicTool sharePlay].pross = @"0";
}
#pragma mark 下载
#pragma mark 点击方法
-(void)load:(UIButton *)bu{
    
    ZCDetailListModel *model = self.songArr[bu.tag];
    if(model.auditionList.count == 0) return;
    NSString *str = [model.name stringByAppendingString:@".mp3"];
    NSLog(@"%@",str);
    [[ZCDownLoadTool shareDownLoad] addDownloadTask:str urlStr:model.auditionList[0][@"url"] singer:model.singerName];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
